﻿using System;
using System.Collections.Generic;
using AutoMapper;
using ERP.BLL.DepotApp.Dtos;
using ERP.Common.Extensions;
using ERP.Common.Model;
using ERP.IDAL.IRepositories.basic;
using ERP.Model.Entities;

namespace ERP.BLL.DepotApp
{
    public class DepotService : IDepotService
    {
        private readonly IDepotRepository _depotRepository;

        public DepotService(IDepotRepository depotRepository)
        {
            _depotRepository = depotRepository;
        }

        public PagedResultModel<DepotDto> GetDepotPageList(int pageIndex, int pageSize)
        {
            return Mapper.Map<List<DepotDto>>(_depotRepository.LoadPageList(pageIndex, pageSize, out var rowCount, t => true,
                    t => t.Id, false)).ApplyToPage(pageIndex, pageSize, rowCount);
        }

        public int Insert(DepotDto dto)
        {
            var depot = _depotRepository.FirstOrDefaultAsync(t => t.Name == dto.Name).Result;
            return depot != null ? 1 : (_depotRepository.Insert(Mapper.Map<Depot>(dto)) != null ? 0 : 1);
        }

        public bool Update(DepotDto dto)
        {
            return _depotRepository.UpdateAsync(Mapper.Map<Depot>(dto)).Result != null;
        }

        public void Delete(Guid id)
        {
            _depotRepository.Delete(id);
        }
    }
}